<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索 -->
    <div>
      <el-input placeholder="请输入内容" v-model="searchVal" class="search-input">
        <el-button slot="append" icon="el-icon-search" @click="serchUser"></el-button>
      </el-input>
      <el-button type="primary" plain @click="addClick">添加用户</el-button>
    </div>
    <!-- 数据列表 -->
    <el-table class="mt-15 mb-15" v-loading="loading" border :data="tableData" style="width: 100%">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <!-- 状态编辑 -->
      <el-table-column prop="mg_state" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#c7c7c7"
            @change="statusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <!-- 编辑，删除操作部分 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            circle
            @click="handleEdit(scope.$index, scope.row)"
          ></el-button>
          <el-button
            size="mini"
            type="warning"
            circle
            icon="el-icon-check"
            @click="handleCheck(scope.$index, scope.row)"
          ></el-button>
          <el-button
            size="mini"
            icon="el-icon-delete"
            circle
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addFormVisible">
      <el-form :model="addForm" :rules="addrules" ref="addref">
        <el-form-item label="用户名" prop="username" label-width="90px">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="90px">
          <el-input v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="90px">
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile" label-width="90px">
          <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑对话框部分 -->
    <el-dialog title="编辑用户" :visible.sync="editFormVisible">
      <el-form :model="editForm" :rules="editrules">
        <el-form-item label="用户名" prop="username" label-width="90px">
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="90px">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile" label-width="90px">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="角色分配" :visible.sync="checkFormVisible">
      <el-form :model="checkForm">
        <el-form-item label="当前用户" label-width="90px">
          <el-tag type="warning">{{checkForm.username}}</el-tag>
        </el-form-item>
        <el-form-item label="请选择角色" label-width="90px">
          <el-select v-model="selectId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="isRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalNum"
    ></el-pagination>
  </div>
</template>
<script>
import {
  getlistdata,
  addUsers,
  editUser,
  deleteUser,
  changeStatus,
  getRoleList,
  checkRole
} from "@/api";
export default {
  data() {
    let checkEmail = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("输入不能为空"));
      } else {
        let emailReg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
        if (emailReg.test(value)) {
          callback();
        } else {
          callback(new Error("邮箱格式不正确"));
        }
      }
    };
    return {
      searchVal: "",
      tableData: [],
      addFormVisible: false,
      editFormVisible: false,
      checkFormVisible: false,
      loading: true,
      pagesize: 10,
      currentPage: 1,
      totalNum: 0,

      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editForm: {
        username: "",
        email: "",
        mobile: "",
        id: ""
      },
      roleList: [],
      selectId: "",
      checkForm: {
        username: "",
        roleId: ""
      },
      addrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 5, max: 10, message: "长度在 5 到 10个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 10, message: "长度在 5 到 10个字符", trigger: "blur" }
        ],
        email: [
          { required: true, validator: checkEmail, trigger: ["blur", "change"] }
        ],
        mobile: [{ required: true, message: "请输入电话号码", trigger: "blur" }]
      },
      editrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 5, max: 10, message: "长度在 5 到 10个字符", trigger: "blur" }
        ],
        email: [
          { required: true, validator: checkEmail, trigger: ["blur", "change"] }
        ],
        mobile: [{ required: true, message: "请输入电话号码", trigger: "blur" }]
      }
    };
  },
  created() {
    this.initlist();
  },
  methods: {
    initlist() {
      this.loading = true;
      getlistdata({
        query: this.searchVal,
        pagenum: this.currentPage,
        pagesize: this.pagesize
      }).then(res => {
        console.log(res)
        this.tableData = res.data.data.users;
        this.totalNum = res.data.data.total;
        this.loading = false;
      });
    },
    serchUser() {
      this.currentPage = 1;
      this.initlist();
    },
    addUser() {
      addUsers(this.addForm).then(res => {
        if (res.data.meta.status == 201) {
          this.$message.success(res.data.meta.msg);
          this.addFormVisible = false;
          this.initlist();
          this.addForm.username = "";
          this.addForm.email = "";
          this.addForm.mobile = "";
          this.addForm.password = "";
        } else {
          this.$message.error(res.data.meta.msg);
        }
      });
    },
    handleEdit(index, row) {
      this.editFormVisible = true;
      this.editForm.username = row.username;
      this.editForm.email = row.email;
      this.editForm.mobile = row.mobile;
      this.editForm.id = row.id;
    },
    editUser() {
      editUser(this.editForm).then(res => {
        console.log(res);
        if (res.data.meta.status == 200) {
          this.$message.success(res.data.meta.msg);
          this.editFormVisible = false;
          this.initlist();
        } else {
          this.$message.error(res.data.meta.msg);
        }
      });
    },
    addClick() {
      this.addFormVisible = true;
      this.$nextTick(() => {
        this.$refs.addref.clearValidate();
      });
    },
    handleCheck(index, row) {
      console.log(row)
      this.checkFormVisible = true;
      this.checkForm.username = row.username;
      this.checkForm.roleId = row.id;
      this.selectId = row.role_name;
      getRoleList().then(res => {
        this.roleList = res.data.data;
      });
    },
    isRole() {
      if(typeof this.selectId=="string"){
        this.checkFormVisible = false;
        return false
      }
      checkRole(this.checkForm.roleId, this.selectId).then(res => {
        if (res.data.meta.status == 200) {
          this.$message.success(res.data.meta.msg);
          this.checkFormVisible = false;
          this.initlist();
        } else {
           console.log(res)
          this.$message.error(res.data.meta.msg);
        }
      });
    },

    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteUser(row.id).then(res => {
            if (res.data.meta.status === 200) {
              this.$message.success(res.data.meta.msg);
              this.initlist();
            } else {
              this.$message.error(res.data.meta.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    statusChange(row) {
      changeStatus(row.id, row.mg_state).then(res => {
        if (res.data.meta.status === 200) {
          this.$message.success(res.data.meta.msg);
          this.initlist();
        } else {
          this.$message.error(res.data.meta.msg);
        }
      });
    },

    handleSizeChange(val) {
      this.pagesize = val;
      this.initlist();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initlist();
    }
  }
};
</script>
<style>
.search-input {
  width: 300px;
  margin-right: 20px;
}
</style>
